package com.rongdong.parkingcapture.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rongdong.parkingcapture.common.R;
import com.rongdong.parkingcapture.domain.Task;
import com.rongdong.parkingcapture.domain.vo.TaskIdVO;
import com.rongdong.parkingcapture.domain.vo.TaskVO;
import com.rongdong.parkingcapture.service.impl.TaskServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

import static com.rongdong.parkingcapture.constant.Constants.SUCCESS_MESSAGE;
import static com.rongdong.parkingcapture.constant.Constants.TASK_ID;

/**
 * Task控制层
 */
@RestController
@RequestMapping("index/api")
public class TaskController {

    @Resource
    TaskServiceImpl taskService;

    /**
     * 创建任务
     */
    @PostMapping("/add_task")
    public R<TaskIdVO> addTask(@RequestBody Task task) {
        task.setCreateTime(new Date());
        //查询数据库是否有该taskId
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(TASK_ID, task.getTaskId());
        boolean exists = taskService.exists(queryWrapper);
        if (exists) {
            return R.fail("add task failure");
        }

        //存入数据，将json对象类型转换为字符串类型
        boolean isSave = taskService.save(taskService.objectToString(task));
        if (!isSave) {
            return R.fail("add task failure");
        }
        //返回值处理
        TaskIdVO taskIdVO = new TaskIdVO();
        taskIdVO.setTaskId(task.getTaskId());
        return R.ok(taskIdVO, SUCCESS_MESSAGE);
    }

    /**
     * 销毁任务
     */
    @PostMapping("/del_task")
    public R<TaskIdVO> deleteTask(@RequestParam String taskId) {
        boolean isDelete = taskService.removeById(taskId);
        if (!isDelete) {
            return R.fail("del task failure");
        }

        TaskIdVO taskIdVO = new TaskIdVO();
        taskIdVO.setTaskId(taskId);
        return R.ok(taskIdVO, SUCCESS_MESSAGE);
    }

    /**
     * 查询任务
     */
    @PostMapping("/get_task")
    public R<TaskVO> getTask(@RequestParam String taskId) {
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(TASK_ID, taskId);
        boolean exists = taskService.exists(queryWrapper);
        if (!exists) {
            return R.fail("get task failure");
        }
        Task task = taskService.stringToObject(taskService.getById(taskId));
        TaskVO taskVO = new TaskVO();
        BeanUtils.copyProperties(task, taskVO);
        return R.ok(taskVO, "Task exists");
    }

}
